import { fileURLToPath, URL } from 'node:url'
import { ConfigEnv, loadEnv, UserConfigExport } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import tailwindcss from '@tailwindcss/vite'

// 自定义组件解析器
const KitegoResolver = (name: string) => {
    if (name.startsWith('kitego')) {
        return {
            name: name.toLowerCase(),
            from: `@/components/${name.toLowerCase()}`
        }
    }
}

export default ({ mode }: ConfigEnv): UserConfigExport => {
    const env = loadEnv(mode, process.cwd())

    return {
        base: env.VITE_BASE_URL,
        logLevel: 'warn',
        plugins: [
            vue(),
            vueJsx(),
            vueDevTools(),
            tailwindcss(),
            AutoImport({
                resolvers: [ElementPlusResolver()],
                include: [/.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
                imports: [
                    'vue',
                    'vue-router',
                    'vue-i18n',
                    {
                        '@vueuse/core': ['useMouse', ['useFetch', 'useMyFetch']],
                        axios: [['default', 'axios']]
                    }
                ],
                eslintrc: { enabled: true },
                dts: './auto-imports.d.ts'
            }),
            Components({
                resolvers: [KitegoResolver, ElementPlusResolver()]
            })
        ],
        resolve: {
            alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) }
        },
        optimizeDeps: {
            include: ['amis-editor-core'],
            exclude: []
        },
        publicDir: 'public',
        build: {
            emptyOutDir: true,
            outDir: 'dist',
            minify: 'esbuild',
            chunkSizeWarningLimit: 2000,
            rollupOptions: {
                external: [],
                output: {
                    entryFileNames: `assets/[name].[hash].js`,
                    chunkFileNames: `assets/[name].[hash].js`,
                    assetFileNames: `assets/[name].[hash].[ext]`,
                    manualChunks: (id: string) => {
                        if (id.includes('node_modules')) {
                            return id.toString().split('node_modules/')[1].split('/')[0].toString()
                        }
                    }
                }
            },
            // 关闭 CSS 代码分割，避免样式加载顺序问题
            cssCodeSplit: false,
            // 确保构建目标兼容现代浏览器
            target: 'esnext'
        }
    }
}
